﻿#region License

// Another free, open solution by folks who get it.
// Copyright © 2011 Business in Unison, Inc.
// 
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

#endregion

using System;

using Exortech.NetReflector;

using ThoughtWorks.CruiseControl.Core;
using ThoughtWorks.CruiseControl.Core.Util;

using ILabeler = ThoughtWorks.CruiseControl.Core.ILabeller;

namespace Patterns.CruiseControl
{
	/// <summary>
	/// 	Defines a labeler that always labels the project with a timestamp-based
	/// 	version number. This corresponds perfectly with this project's Rakefile
	/// 	build, as the build will generate the assembly version, also using a
	/// 	timestamp-based formula.  This ensures orthogonal naming conventions
	/// 	between build numbers, assembly versions, and NuGet package versions.
	/// </summary>
	[ReflectorType("dateTimeVersionLabeler")]
	public class DateTimeVersionLabeler : ILabeler
	{
		[ReflectorProperty("prefix", Required = false)]
		public string LabelPrefix { get; set; }

		[ReflectorProperty("suffix", Required = false)]
		public string LabelSuffix { get; set; }

		[ReflectorProperty("majorVersion", Required = false)]
		public string MajorVersion { get; set; }

		[ReflectorProperty("minorVersion", Required = false)]
		public string MinorVersion { get; set; }

		#region ILabeller Members

		public void Run(IIntegrationResult result)
		{
			string label = Generate(result);
			Log.Info("Setting build label to {0}", label);
			result.Label = label;
		}

		public string Generate(IIntegrationResult integrationResult)
		{
			Log.Info("Generating build number...");

			try
			{
				string version = GetNewVersion();
				return string.Format("{0}{1}{2}", LabelPrefix, version, LabelSuffix);
			}
			catch (Exception ex)
			{
				Log.Error("An error occurred while attempting to generate build number!");
				Log.Error(ex);
				throw;
			}
		}

		#endregion

		private string GetNewVersion()
		{
			string major = MajorVersion ?? "0";
			string minor = MinorVersion ?? DateTime.Now.Year.ToString();
			string build = DateTime.Now.DayOfYear.ToString();
			string revision = DateTime.Now.ToString("Hmm");
			return string.Format("{0}.{1}.{2}.{3}", major, minor, build, revision);
		}
	}
}